package array;

/**
 * Given an integer array nums, return the number of subarrays of length 3 such that the sum of the first and third
 * numbers equals exactly half of the second number.
 * <p>
 * Example 1:
 * Input: nums = [1,2,1,4,1]
 * Output: 1
 * Explanation:
 * Only the subarray [1,4,1] contains exactly 3 elements where the sum of the first and third numbers equals half the
 * middle number.
 * <p>
 * Example 2:
 * Input: nums = [1,1,1]
 * Output: 0
 * Explanation:
 * [1,1,1] is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.
 *
 * @author Jisheng Huang
 * @version 20250427
 */
public class CountSubarrays_3392 {
    /**
     * Loop through the array from 0 to nums.length - 2 to check whether 2 *(nums[i] + nums[i + 2]) == nums[i + 1]
     *
     * @param nums the given integer array
     * @return the number of valid formation
     */
    public static int countSubArray(int[] nums) {
        int cnt = 0;

        for (int i = 0; i < nums.length - 2; ++i) {
            if ((nums[i] + nums[i + 2]) * 2 == nums[i + 1]) {
                ++cnt;
            }
        }

        return cnt;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 1, 4, 1};
        System.out.println(countSubArray(arr));

        arr = new int[]{1, 1, 1};
        System.out.println(countSubArray(arr));
    }
}
